axios.defaults.baseURL = 'https://hmajax.itheima.net'


//添加请求拦截器 
axios.interceptors.request.use(config => {
    // Do something before request is sent
    const token = getItem('token')
    if (token) {
        config.headers.Authorization = token
    }
    return config;
}, error => {
    // Do something with request error
    return Promise.reject(error);
});


//添加响应器
axios.interceptors.response.use(response => {
    // Do something before response is sent
    return response.data;
}, error => {
    if (error.response.status === 401) {
        //清空本地存储
        removeItem('token')
        removeItem('username')
        //给出提示
        showToast('token已失效，请重新登录')
        //跳转到登录页面
        setTimeout(() => {
            location.href = 'login.html'
        }, 1500);
    }
    // Do something with response error
    return Promise.reject(error);
});


//2.抽取提示函数
function showToast(msg = '提示消息') {
    //1 找到toast标签
    const toast = document.querySelector('.my-toast')
    //2 创建Toast实例对象
    const toastObj = new bootstrap.Toast(toast)
    //3.修改提示信息
    document.querySelector('.toast-body').innerText = msg
    //4 显示Toast
    toastObj.show()
}
//3.封装本地存储
function setItem(key, value) {
    if (typeof value === 'object') {
        value = JSON.stringify(value)
    }
    localStorage.setItem(key, value)
}

4//取数据
function getItem(key) {
    let value = localStorage.getItem(key)
    try {
        return JSON.parse(value)
    } catch (error) {
        return value
    }
}

//删除数据
function removeItem(key) {
    localStorage.removeItem(key)
}

//封装校验登录函数
function checkLogin() {
    // const token = sessionStorage.getItem('token')
    const token = getItem('token')
    if (token == null) {
        showToast('当前用户未登录，请先登录')
        setTimeout(() => {
            location.href = 'login.html'
        }, 1500);
    }
}
//封装渲染用户名函数
function randerUsername() {
    const username = getItem('username')
    if (username) {
        document.querySelector('.username').innerHTML = username
    }
}

//6 封装退出函数
function logOut() {
    //设置点击事件
    const logout = document.querySelector('#logout');
    //给出询问框
    logout.addEventListener('click', function () {
        if (confirm('确认要退出吗')) {
            //清空本地存储
            removeItem('token')
            removeItem('username')
            //返回登录页面
            location.href = 'login.html'
        }
    })
}